const express = require('express');
const router = express.Router();
const db = require('../../../MySql');
const { formatDateTime } = require('../../utils/dateUtils')
const { generate19DigitId } = require('../../utils/idUtils')
const el_paper = require('../../models/el_paper')
const el_exam = require('../../models/el_exam')
const el_exam_repo = require('../../models/el_exam_repo')
const el_paper_qu = require('../../models/el_paper_qu')
const el_qu_repo = require('../../models/el_qu_repo');
const el_qu_answer = require('../../models/el_qu_answer');
const el_paper_qu_answer = require('../../models/el_paper_qu_answer');
const el_qu = require('../../models/el_qu');
const sys_user = require('../../models/sys_user');
const el_user_book = require('../../models/el_user_book');

router.post('/paper/paper/check-process', async (req, res) => {
    try {
        const { userId } = req.body
        //查询el_paper考试记录表是否存在该考试的记录,0 正在考试 ,1 没有正在考试，2 已考完
        const examResults = await el_paper.findByPaperStateAndUserId(0, userId)

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": examResults[0],
            "success": true
        })
    } catch (error) {
        return res.status(500).json({
            msg: error.message,
            code: 500,
            success: false
        })
    }
})


router.post('/paper/paper/create-paper', async (req, res) => {
    const connection = await db.getConnection()
    try {
        const { examId, userId } = req.body

        //查询el_paper考试记录表是否存在该考试的记录,0 正在考试 ,1 没有正在考试，2 已考完
        const checkProcess = await el_paper.findByPaperStateAndUserId(0, userId)
        if (checkProcess.length > 0) {
            return res.json({ "msg": "您有正在进行的考试！", "code": 20010002, "success": false })
        }

        //根据考试id查询考试信息
        const examResults = await el_exam.findExamById(examId)

        //开始考试，向el_paper考试记录表新增一条考试记录,0 正在考试 ,1 没有正在考试，2 已考完
        const paper = {
            id: generate19DigitId(),
            user_id: userId,
            depart_id: 1318103313740320770,
            exam_id: examId,
            title: examResults.title,
            total_time: examResults.total_time,
            user_time: 0,
            total_score: examResults.total_score,
            qualify_score: examResults.qualify_score,
            obj_score: 0,
            subj_score: 0,
            user_score: 0,//用户成绩
            has_saq: 0,//是否包含简答题
            state: 0,//考试状态,0 正在考试 ,1 没有正在考试，2 已考完
        }

        // 新增考试记录
        await el_paper.insertPaper(paper)

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": paper.id,
            },
            "success": true
        })
    } catch (error) {
        await connection.rollback()
        console.error('生成试卷失败:', error)
        return res.status(500).json({
            msg: "生成试卷失败: " + error.message,
            code: 500,
            success: false
        })
    } finally {
        connection.release()
    }
})

router.post('/paper/paper/paper-detail', async (req, res) => {
    const connection = await db.getConnection()
    try {
        const { id } = req.body

        // 计算离开的时间
        // 根据id查询考试记录
        //const [result] = await db.query('select user_time, create_time ,total_time from el_paper where id=?', [id])
        const result = await el_paper.findPaperById(id)

        const currentTime = Math.floor(Date.now() / 1000)  // 当前时间戳（秒）
        const createTime = Math.floor(new Date(result.create_time).getTime() / 1000)  // 考试开始时间戳（秒）
        const durationSeconds = currentTime - createTime  // 总用时（秒）

        const totalSeconds = result.total_time * 60  // 考试总秒数
        const leftSeconds = Math.max(0, totalSeconds - durationSeconds)  // 剩余秒数（精确到个位）

        const durationMinutes = Math.floor(durationSeconds / 60)  // 转换为分钟

        // 更新数据库中的用户时长
        //await db.query('update el_paper set user_time=? where id=?', [durationMinutes, id])
        await el_paper.updateUserTime(id, durationMinutes)

        //查询el_paper考试记录表
        //const [results] = await db.query('select * from el_paper where id=?', [id])
        const results = await el_paper.findPaperById(id)

        //通过exam_id查询el_exam_repo关联的题库
        //const [repoRes] = await db.query('select * from el_exam_repo where exam_id=?', [results[0].exam_id])
        const repoRes = await el_exam_repo.findExamRepoByExamId(results.exam_id)

        //查询每种题目类型的单题分值
        // const [radioScoreRes] = await db.query('select radio_score from el_exam_repo where exam_id=?', [results[0].exam_id])
        // const [multiScoreRes] = await db.query('select multi_score from el_exam_repo where exam_id=?', [results[0].exam_id])
        // const [judgeScoreRes] = await db.query('select judge_score from el_exam_repo where exam_id=?', [results[0].exam_id])
        const rows = await el_exam_repo.findExamRepoByExamId(results.exam_id)
        const radioScoreRes = rows[0].radio_score
        const multiScoreRes = rows[0].multi_score
        const judgeScoreRes = rows[0].judge_score

        //通过repo_id查询el_paper_qu关联的题目
        //const [quRes] = await db.query('select * from el_qu_repo where repo_id=?', [repoRes[0].repo_id])
        const quRes = await el_qu_repo.findQuRepoByRepoId(repoRes[0].repo_id)

        //检查是否已经为该试卷生成了题目记录
        //const [existingQuestions] = await connection.query('select * from el_paper_qu where paper_id=?', [id])
        const existingQuestions = await el_paper_qu.findPaperQuByPaperId(id)

        const existingQuestionFormate = existingQuestions.map(item => ({
            "id": item.id,
            "paperId": item.paper_id,
            "quId": item.qu_id,
            "quType": item.qu_type,
            "answered": item.answered == 1 ? true : false,
            "answer": item.answer || "",
            "sort": item.sort,
            "score": item.score,
            "actualScore": item.actual_score,
            "isRight": item.is_right == 1 ? true : false
        }))

        //如果已经存在题目记录，直接返回现有记录
        if (existingQuestionFormate.length > 0) {
            //按题目类型分类现有题目
            const radioList = existingQuestionFormate.filter(item => item.quType == 1).sort((a, b) => a.sort - b.sort)
            const multiList = existingQuestionFormate.filter(item => item.quType == 2).sort((a, b) => a.sort - b.sort)
            const judgeList = existingQuestionFormate.filter(item => item.quType == 3).sort((a, b) => a.sort - b.sort)

            return res.json({
                "msg": "操作成功！",
                "code": 0,
                "data": {
                    "id": id,
                    "userId": results.user_id,
                    "departId": results.depart_id,
                    "examId": results.exam_id,
                    "title": results.title,
                    "totalTime": results.total_time,
                    "userTime": results.user_time,
                    "totalScore": results.total_score,
                    "qualifyScore": results.qualify_score,
                    "objScore": results.obj_score,
                    "subjScore": results.subj_score,
                    "userScore": results.user_score,
                    "hasSaq": results.has_saq == 1 ? true : false,
                    "state": results.state,
                    "createTime": results.create_time,
                    "updateTime": results.update_time,
                    "limitTime": results.limit_time,
                    "radioList": radioList,
                    "multiList": multiList,
                    "judgeList": judgeList,
                    "leftSeconds": leftSeconds
                },
                "success": true
            })
        }

        //如果不存在题目记录，则生成新题目并插入
        //根据el_paper_qu的单选题、多选题、判断题数量，生成对应题目数量的试卷
        //单选题
        const radioListRes = quRes.filter(item => item.qu_type == 1).sort(() => Math.random() - 0.5).slice(0, repoRes[0].radio_count)
        //多选题
        const multiListRes = quRes.filter(item => item.qu_type == 2).sort(() => Math.random() - 0.5).slice(0, repoRes[0].multi_count)
        //判断题
        const judgeListRes = quRes.filter(item => item.qu_type == 3).sort(() => Math.random() - 0.5).slice(0, repoRes[0].judge_count)

        let radioList = radioListRes.map((item, index) => ({
            "id": item.id,
            "paperId": id,
            "quId": item.qu_id,
            "quType": item.qu_type,
            "answered": item.answered == 1 ? true : false,
            "answer": "",
            "sort": index,
            "score": radioScoreRes || null,
            "actualScore": radioScoreRes || null,
            "isRight": 0
        })).sort((a, b) => a.sort - b.sort)

        const multiList = multiListRes.map((item, index) => ({
            "id": item.id,
            "paperId": id,
            "quId": item.qu_id,
            "quType": item.qu_type,
            "answered": item.answered == 1 ? true : false,
            "answer": "",
            "sort": radioList.length + index,
            "score": multiScoreRes || null,
            "actualScore": multiScoreRes || null,
            "isRight": 0
        }))

        const judgeList = judgeListRes.map((item, index) => ({
            "id": item.id,
            "paperId": id,
            "quId": item.qu_id,
            "quType": item.qu_type,
            "answered": item.answered == 1 ? true : false,
            "answer": "",
            "sort": radioList.length + multiList.length + index,
            "score": judgeScoreRes || null,
            "actualScore": judgeScoreRes || null,
            "isRight": 0
        })).sort((a, b) => a.sort - b.sort)

        //随机生成题目后，向el_paper_qu表新增记录
        //单选题
        for (const item of radioList) {
            const paperQu = {
                id: generate19DigitId(),
                paper_id: id,
                qu_id: item.quId,
                qu_type: item.quType,
                answered: item.answered,
                answer: item.answer,
                sort: item.sort,
                score: item.score,
                actual_score: item.actualScore,
                is_right: item.isRight
            }

            await el_paper_qu.insertPaperQu(paperQu)

            // await connection.query('insert into el_paper_qu (id, paper_id, qu_id, qu_type, answered, sort, score, actual_score, is_right) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', [
            //     generate19DigitId(),
            //     id,
            //     item.quId,
            //     item.quType,
            //     item.answered,
            //     item.sort,
            //     item.score,
            //     item.actualScore,
            //     item.isRight
            // ])
        }

        //多选题
        for (const item of multiList) {
            const paperQu = {
                id: generate19DigitId(),
                paper_id: id,
                qu_id: item.quId,
                qu_type: item.quType,
                answered: item.answered,
                answer: item.answer,
                sort: item.sort,
                score: item.score,
                actual_score: item.actualScore,
                is_right: item.isRight
            }

            await el_paper_qu.insertPaperQu(paperQu)
            // await db.query('insert into el_paper_qu (id, paper_id, qu_id, qu_type, answered, sort, score, actual_score, is_right) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', [
            //     generate19DigitId(),
            //     id,
            //     item.quId,
            //     item.quType,
            //     item.answered,
            //     item.sort,
            //     item.score,
            //     item.actualScore,
            //     item.isRight
            // ])
        }

        //判断题
        for (const item of judgeList) {
            const paperQu = {
                id: generate19DigitId(),
                paper_id: id,
                qu_id: item.quId,
                qu_type: item.quType,
                answered: item.answered,
                answer: item.answer,
                sort: item.sort,
                score: item.score,
                actual_score: item.actualScore,
                is_right: item.isRight
            }

            await el_paper_qu.insertPaperQu(paperQu)
            // await connection.query('insert into el_paper_qu (id, paper_id, qu_id, qu_type, answered, sort, score, actual_score, is_right) values (?, ?, ?, ?, ?, ?, ?, ?, ?)', [
            //     generate19DigitId(),
            //     id,
            //     item.quId,
            //     item.quType,
            //     item.answered,
            //     item.sort,
            //     item.score,
            //     item.actualScore,
            //     item.isRight
            // ])
        }

        //向el_paper_qu_answer表新增记录      
        for (const item of [...radioList, ...multiList, ...judgeList]) {
            // const [answerList] = await connection.query('select * from el_qu_answer where qu_id = ?', [item.quId])
            const answerList = await el_qu_answer.findQuAnswerByQuId(item.quId)

            //为每个选项插入记录
            for (let i = 0; i < answerList.length; i++) {
                const answer = answerList[i]

                const paperQuAnswer = {
                    id: generate19DigitId(),
                    paper_id: id,
                    answer_id: answer.id,
                    qu_id: item.quId,
                    is_right: answer.is_right,
                    checked: 0,
                    sort: i + 1,  // sort从1开始
                    abc: ['A', 'B', 'C', 'D', 'E'][i]  // 对应的字母
                }

                await el_paper_qu_answer.insertPaperQuAnswer(paperQuAnswer)
                // await connection.query('insert into el_paper_qu_answer (id, paper_id, answer_id, qu_id, is_right, checked, sort, abc) values (?, ?, ?, ?, ?, ?, ?, ?)', [
                //     generate19DigitId(),
                //     id,
                //     answer.id,
                //     item.quId,
                //     answer.is_right,
                //     0,
                //     i + 1,  // sort从1开始
                //     ['A', 'B', 'C', 'D', 'E'][i]  // 对应的字母
                // ])
            }
        }

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": id,
                "userId": results.user_id,
                "departId": results.depart_id,
                "examId": results.exam_id,
                "title": results.title,
                "totalTime": results.total_time,
                "userTime": results.user_time,
                "totalScore": results.total_score,
                "qualifyScore": results.qualify_score,
                "objScore": results.obj_score,
                "subjScore": results.subj_score,
                "userScore": results.user_score,
                "hasSaq": results.has_saq == 1 ? true : false,
                "state": results.state,
                "createTime": results.create_time,
                "updateTime": results.update_time,
                "limitTime": results.limit_time,
                "radioList": radioList,
                "multiList": multiList,
                "judgeList": judgeList,
                "leftSeconds": leftSeconds
            },
            "success": true
        })
    } catch (error) {
        connection.rollback()
        console.error('数据库查询失败:', error)
        return res.status(500).json({
            msg: "数据库查询失败: " + error.message,
            code: 500,
            success: false
        });
    } finally {
        connection.release()
    }
})

router.post('/paper/paper/qu-detail', async (req, res) => {
    try {
        const { paperId, quId } = req.body

        const abc = ['A', 'B', 'C', 'D', 'E']

        const results = await el_paper_qu.findPaperQuByPaperIdAndQuId(paperId, quId)

        const answerListRes = await el_qu.findQuById(quId)

        const answerListRes2 = await el_paper_qu_answer.findPaperQuAnswerByPaperIdAndQuId(paperId, quId)

        const answerDetail = await el_qu_answer.findQuAnswerByQuId(quId)

        const answerList = answerListRes2.map((item, index) => ({
            "id": item.id,
            "paperId": item.paper_id,
            "answerId": item.id,
            "quId": quId,
            "checked": item.checked == 1 ? true : false,
            "sort": index,
            "abc": abc[index],
            "image": answerDetail[index].image || null,
            "content": answerDetail[index].content
        }))

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": results.id,
                "paperId": results.paper_id,
                "quId": results.qu_id,
                "quType": results.qu_type,
                "answered": results.answered == 1 ? true : false,
                "answer": results.answer,
                "sort": results.sort,
                "score": results.score,
                "actualScore": results.actual_score,
                "isRight": results.is_right == 1 ? true : false,
                "image": answerListRes.image || null,
                "content": answerListRes.content,
                "answerList": answerList
            },
            "success": true
        })
    } catch (error) {
        console.error(error)
        return res.json({
            msg: "数据库查询失败: " + error.message,
            code: 500,
            success: false
        });
    }
})


router.post('/paper/paper/fill-answer', async (req, res) => {
    try {
        const { paperId, quId, answers } = req.body

        //对el_paper_qu的answered字段进行更新
        await el_paper_qu.updateAnswered(paperId, quId, 1)

        //对el_paper_qu_answer的checked字段更新
        await el_paper_qu_answer.updateChecked(quId)

        if (answers && answers.length > 0) {
            // 构建IN查询参数
            const placeholders = answers.map(() => '?').join(',')
            await db.query(`update el_paper_qu_answer set checked=1 where qu_id=? and id in (${placeholders})`, [quId, ...answers])
        }

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error(error)
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        });
    }
})

router.post('/paper/paper/hand-exam', async (req, res) => {
    try {
        const { id } = req.body

        // 计算离开的时间
        const result = await el_paper.findPaperById(id)

        const currentTime = Math.floor(Date.now() / 1000)  // 当前时间戳（秒）
        const createTime = Math.floor(new Date(result.create_time).getTime() / 1000)  // 考试开始时间戳（秒）
        const durationSeconds = currentTime - createTime  // 总用时（秒）
        const durationMinutes = Math.floor(durationSeconds / 60)  // 转换为分钟

        // 更新数据库中的用户时长和考试状态，2 已考完，1 待阅卷
        await el_paper.updateUserTimeAndState(id, durationMinutes, 2)

        // 更新考试更新时间
        await el_paper.updateUpdateTime(id)

        const results = await el_paper.findPaperById(id)

        // 使用Math.max计算所有考试记录中的最高分
        const max_scoreRes = await el_paper.findPaperByExamIdAndUserId(results.exam_id, results.user_id)
        const max_score = Math.max(...max_scoreRes.map(item => item.userScore))

        // 更新el_user_exam的try_count字段和max_score字段和passed，update_time字段
        // 统计el_paper的考试次数更新el_user_exam表的try_count字段
        const [examCountRes] = await db.query('select count(*) as count from el_paper where exam_id=? and user_id=?', [results.exam_id, results.user_id])
        const tryCount = examCountRes[0].count

        //如果el_user_exam表中没有对应考试记录，则插入，否则更新
        const [user_examRes] = await db.query('select * from el_user_exam where exam_id=? and user_id=?', [results.exam_id, results.user_id])
        if (user_examRes.length === 0) {
            // 插入新记录 
            await db.query('insert into el_user_exam (id,exam_id, user_id, try_count, max_score,create_time, update_time) values (?, ?, ?, ?, ?, NOW(), NOW())', [generate19DigitId(), results.exam_id, results.user_id, tryCount, max_score])
        } else {
            // 更新记录
            await db.query('update el_user_exam set try_count=?,max_score=?,update_time=NOW() where exam_id=? and user_id=?', [tryCount, max_score, results.exam_id, results.user_id])
        }

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error(error)
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        })
    }
})


router.post('/paper/paper/paper-result', async (req, res) => {
    try {
        const { id } = req.body

        const answerListRes = await el_paper_qu_answer.findPaperQuAnswerByPaperId(id)

        const quListRes = await el_paper_qu.findPaperQuByPaperId(id)

        // 为每个题目查询对应的el_qu内容
        let quList = await Promise.all(quListRes.map(async (item) => {
            const answerListContentRes = await el_qu.findQuById(item.qu_id)

            // 为每个题目查询选项内容
            const answerListWithContent = await Promise.all(answerListRes.map(async (answerItem) => {
                if (answerItem.qu_id === item.qu_id) {
                    const optionContentRes = await el_qu_answer.findQuAnswerById(answerItem.answer_id)
                    return {
                        "id": answerItem.id,
                        "paperId": answerItem.paper_id,
                        "answerId": answerItem.answer_id,
                        "quId": answerItem.qu_id,
                        "isRight": answerItem.is_right == 1 ? true : false,
                        "checked": answerItem.checked == 1 ? true : false,
                        "sort": answerItem.sort,
                        "abc": answerItem.abc,
                        "image": "",
                        "content": optionContentRes.content || ''
                    }
                }
                return null
            }))

            // 过滤掉null值
            const filteredAnswerList = answerListWithContent.filter(item => item !== null)

            // 计算题目是否正确
            let isQuestionRight = false

            if (item.qu_type === 1) {
                // 单选题：必须选中且只选中一个正确选项
                const checkedAnswers = filteredAnswerList.filter(answer => answer.checked)
                if (checkedAnswers.length === 1) {
                    isQuestionRight = checkedAnswers[0].isRight
                    await el_paper_qu.updateIsRight(checkedAnswers[0].paperId, item.qu_id, isQuestionRight === true ? 1 : 0)
                }
            } else if (item.qu_type === 2) {
                // 多选题：必须选中所有正确选项，且不能选中错误选项
                const correctAnswers = filteredAnswerList.filter(answer => answer.isRight)
                const checkedAnswers = filteredAnswerList.filter(answer => answer.checked)
                const checkedCorrectAnswers = checkedAnswers.filter(answer => answer.isRight)

                isQuestionRight = (checkedAnswers.length === correctAnswers.length) &&
                    (checkedCorrectAnswers.length === correctAnswers.length)
                await el_paper_qu.updateIsRight(filteredAnswerList[0].paperId, item.qu_id, isQuestionRight === true ? 1 : 0)
            } else if (item.qu_type === 3) {
                // 判断题：必须选中且只选中一个正确选项
                const checkedAnswers = filteredAnswerList.filter(answer => answer.checked)
                if (checkedAnswers.length === 1) {
                    isQuestionRight = checkedAnswers[0].isRight
                    await el_paper_qu.updateIsRight(checkedAnswers[0].paperId, item.qu_id, isQuestionRight === true ? 1 : 0)
                }
            }

            // 如果用户没有答题（没有选中任何选项），则题目答错
            const hasAnswered = filteredAnswerList.some(answer => answer.checked);
            if (!hasAnswered) {
                isQuestionRight = false
            }

            return {
                "id": item.id,
                "paperId": item.paper_id,
                "quId": item.qu_id,
                "quType": item.qu_type,
                "answered": hasAnswered, // 更新答题状态
                "answer": item.answer,
                "sort": item.sort,
                "score": item.score,
                "actualScore": item.actual_score,
                "isRight": isQuestionRight,
                "image": "",
                "content": answerListContentRes.content || '',
                "answerList": filteredAnswerList
            }
        }))


        quList.sort((a, b) => (a.sort - b.sort))

        // 根据选项更新el_paper的主客观题的分数
        // 根据quList的isRight字段计算成绩
        let objScore = 0 // 客观题分数
        let subjScore = 0 // 主观题分数
        let userScore = 0 // 用户总分数

        quList.forEach(question => {
            if (question.isRight) {
                // 题目答对，加上该题分数
                if (question.quType === 1 || question.quType === 2) {
                    // 单选题或多选题 - 客观题
                    objScore += question.score
                } else if (question.quType === 3) {
                    // 主观题
                    subjScore += question.actualScore || question.score
                }
                userScore += question.actualScore || question.score
            }
        })

        // 更新el_paper表的主客观题分数
        await el_paper.updateUserScore(objScore, subjScore, userScore, id)

        const results = await el_paper.findPaperById(id)

        // 根据id查询用户信息
        const userInfo = await sys_user.findUserById(results.user_id)

        //计算是否通过
        const examRes = await el_exam.findExamById(results.exam_id)
        const passed = results.user_score >= examRes.qualify_score ? 1 : 0

        //更新是否通过考试
        await db.query('update el_user_exam set max_score=?,passed=?,update_time=NOW() where exam_id=? and user_id=?', [results.user_score, passed, results.exam_id, results.user_id])


        // 2. 如果不存在记录，则进行统计和新增
        // 通过examId和userId查询用户的所有试卷
        const papers = await el_paper.findPaperByExamIdAndUserId(results.exam_id, results.user_id)
        const paperIds = papers.map(item => item.id)

        // 3. 统计每道题目的错误次数并新增记录
        // 通过试卷id查询所有题目id
        const quIdsResult = []
        for (const paperId of paperIds) {
            const quIds = await el_paper_qu.findPaperQuByPaperIdAndIsUserDelete(paperId, 0)
            quIdsResult.push(...quIds)
        }

        // 统计每道题目的错误次数并新增记录
        const currentTime = new Date()
        const newRecords = []

        //统计quIdsResult中每个元素的qu_id字段的出现次数
        const quIdCounts = quIdsResult.reduce((acc, item) => {
            // 这里item是包含qu_id字段的对象，需要提取qu_id
            const quId = item.qu_id;
            // 初始化acc[quId]，如果不存在则设为0
            if (acc[quId] === undefined) {
                acc[quId] = 0;
            }

            // 如果is_right为0（错误），则计数加1
            if (item.is_right == 0) {
                acc[quId] = acc[quId] + 1
            }
            return acc
        }, {})

        // 查看统计结果
        // console.log('题目ID统计结果:', JSON.stringify(quIdCounts))

        // 筛选出有错误次数的题目ID
        const wrongQuIds = Object.keys(quIdCounts).filter(quId => quIdCounts[quId] > 0)

        // 查看统计结果
        // console.log('错误题目ID列表:', wrongQuIds)

        //el_user_book新增记录
        for (const quId of wrongQuIds) {
            // 查询该题目的详细信息
            const quInfo = await el_qu.findQuById(quId)
            if (!quInfo) continue

            // 构建新增记录
            const record = {
                id: generate19DigitId(),
                exam_id: results.exam_id,
                user_id: results.user_id,
                qu_id: quId,
                create_time: currentTime,
                update_time: currentTime,
                wrong_count: quIdCounts[quId],
                title: quInfo.content,
                sort: newRecords.length + 1 // sort，按新增顺序排序
            }
            newRecords.push(record)

            //检查el_user_book中是否已存在该考试对应的试题记录
            const existingRecord = await el_user_book.findUserBookByExamIdAndUserIdAndQuId(results.exam_id, results.user_id, quId)
            if (existingRecord.length > 0) {
                // 已存在记录，更新wrong_count
                await el_user_book.updateWrongCount(existingRecord[0].id, quIdCounts[quId])
                // console.log(existingRecord[0])
                continue
            }else{
                // 新增记录到数据库
                //console.log(record)
                await el_user_book.addUserBook(record)
            }
        }


        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": results.id,
                "userId": results.user_id,
                "userName": userInfo.user_name || '',
                "realName": userInfo.real_name || '',
                "departId": results.depart_id,
                "examId": results.exam_id,
                "title": results.title,
                "totalTime": results.total_time,
                "userTime": results.user_time,
                "totalScore": results.total_score,
                "qualifyScore": results.qualify_score,
                "objScore": results.obj_score,
                "subjScore": results.subj_score,
                "userScore": results.user_score,
                "hasSaq": results.has_saq == 1 ? true : false,
                "state": results.state,
                "createTime": results.create_time,
                "updateTime": results.update_time,
                "limitTime": results.limit_time,
                "quList": quList
            },
            "success": true
        })
    } catch (error) {
        console.error(error)
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        });
    }
})


router.post('/paper/paper/paging', async (req, res) => {
    try {
        const { current, size } = req.body
        const { examId, userId } = req.body.params

        //const sql = `select * from el_paper where exam_id=? and user_id=?`
        //const [results] = await db.query(sql, [examId, userId])
        // const records = results.map(item => ({
        //     "id": item.id,
        //     "userId": item.user_id,
        //     "departId": item.depart_id,
        //     "examId": item.exam_id,
        //     "title": item.title,
        //     "totalTime": item.total_time,
        //     "userTime": item.user_time,
        //     "totalScore": item.total_score,
        //     "qualifyScore": item.qualify_score,
        //     "objScore": item.obj_score,
        //     "subjScore": item.subj_score,
        //     "userScore": item.user_score,
        //     "hasSaq": item.has_saq == 1 ? true : false,
        //     "state": item.state,
        //     "createTime": formatDateTime(item.create_time),
        //     "updateTime": formatDateTime(item.update_time),
        //     "limitTime": formatDateTime(item.limit_time),
        //     "realName": item.real_name
        // }))
        const records = await el_paper.findPaperByExamIdAndUserId(examId, userId)


        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "records": records,
                "total": records.length,
                "size": size,
                "current": current,
                "orders": [],
                "optimizeCountSql": true,
                "hitCount": false,
                "searchCount": true,
                "pages": 1
            },
            "success": true
        })
    } catch (error) {
        console.error(error)
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        })
    }
})

module.exports = router;